package com.demo.多线程;

/**
 * @Program: java
 * @ClassName PlayerWatcher
 * @Author: liutao
 * @Description: 生产者消费者模型：信号灯法
 * @Create: 2023-10-27 14:07
 * @Version 1.0
 **/


public class PlayerWatcher {
    public static void main(String[] args) {
        TV tv = new TV();
        new Player(tv).start();
        new Watcher(tv).start();
    }


}

class Player extends Thread {
    TV tv;

    public Player(TV tv) {
        this.tv = tv;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            if (i % 2 == 0) {
                this.tv.player("CCTV-1");
            } else {
                this.tv.player("CCTV-14");
            }
        }
    }
}

class Watcher extends Thread {
    TV tv;

    public Watcher(TV tv) {
        this.tv = tv;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            this.tv.watch();
        }

    }
}

class TV {
    private static volatile boolean flag = true;
    private static String channel;

    public synchronized void player(String channel) {
        if (!flag) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        System.out.println("演员在：" + channel + "表演");
        // 通知观众观看
        this.notifyAll();
        TV.channel = channel;
        flag = !flag;
    }

    public synchronized void watch() {
        if (flag) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        System.out.println("观众观看了：" + channel);
        // 通知演员表演
        this.notifyAll();
        flag = !flag;
    }
}